<template>
  <div class="goods-detail">
      <van-nav-bar :title="goodsInfo.title" left-arrow @click-left="back()" />
    <div class="top-goods">
      <div class="goods-title">
        <div class="top">
          <div class="left">
            <span>{{goodsInfo.title}}</span>
          </div>
          <div class="right">
            <div class="like" v-if="!goodsInfo.is_collect" @click="likeIt">
              <van-icon name="like-o" ref="like" size="0.4rem" color="#c6c5c5" />
            </div>
            <div class="like" v-else-if="goodsInfo.is_collect" @click="likeIt">
              <van-icon name="like" ref="like" size="0.4rem" color="#f8942c" />
            </div>
          </div>
        </div>
        <div class="bottom">
          <div class="now-price">
            ¥ {{goodsInfo.price}}
            <span>活动价</span>
          </div>

          <div class="before-price">
            <del>¥ {{goodsInfo.old_price}}</del>
          </div>
        </div>
      </div>

      <!-- image -->
      <div class="detail-image" v-for="(item,index) in goodsImg" :key="index">
        <van-image fit="contain" lazy-load width="100%"  :src="publicUrl+item.filepath" style="vertical-align: middle;" />
      </div>

      <div class="after-img">
        <div class="left">
          <!-- 77天前 -->
        </div>
        <div class="right">
          <span>
            收藏
            <span ref="collect_goods">{{gcnt}}</span> · 销量 0
          </span>
        </div>
      </div>
    </div>

    <div class="store-detail">
      <div class="store-top">
        <div class="left-head">
          <div class="head" @click="go_store">
            <img v-lazy="publicUrl+shopInfo.filepath" height="100%" width="100%" />
          </div>
        </div>
        <div class="address">
          <div class="store-name">
            <span @click="go_store">{{shopInfo.b_title}}</span>
          </div>
          <div class="add">
            <div
              class="add-icon"
              style="float:left;margin-right:0.06rem;font-size:0.3rem;color:#c6c5ca"
            >
              <van-icon name="location" />
            </div>
            <span
              href="#"
            >{{shopInfo.province}}{{shopInfo.city}}{{shopInfo.county}}{{shopInfo.address}}</span>
          </div>
        </div>
      </div>
      <div class="store-bottom">
        <div class="left">
          <div
            v-if="shopInfo.is_collect"
            ref="likeShop"
            style="background-color:#f8942c;color:#fff"
            @click="likeShop"
          >
            已收藏
            <span ref="collectNum">{{scnt}}</span>
          </div>
          <div v-if="!shopInfo.is_collect" ref="likeShop" @click="likeShop">
            已收藏
            <span ref="collectNum">{{scnt}}</span>
          </div>
        </div>
        <div class="right" @click="go_store">
          <div>进店逛逛</div>
        </div>
      </div>
    </div>

    <!-- 评论 -->
    <div class="comment">
      <div>评论</div>
    </div>

    <div class="no-comment">暂无评论</div>

    <!-- 购买 -->
    <!-- <div class="buy">
      <div class="now-buy" @click="showSheet = true">
        <van-icon name="shopping-cart-o" />
        <span>立即购买</span>
      </div>
    </div> -->
    <div class="buy">
      <div class="now-buy">
        <van-row>
          <van-col span="14" style="text-align: center" @click="showSku = true">
            <van-icon name="shopping-cart-o" />
            <span>立即购买</span>
          </van-col>
          <van-col span="10">
            <van-button @click="handlerConsult" round color="linear-gradient(to top, #ff7700, #fba630)" size="small" style="padding: 0 40px;" type="warning">咨询</van-button>
          </van-col>
        </van-row>
      </div>
    </div>
    <van-action-sheet v-model="showSheet" :actions="actions" @select="onSelect" />
    <van-popup
      v-model="showAddress"
      closeable
      close-icon="close"
      position="bottom"
      :style="{ height: '550px' }"
    >
      <div style="padding-top: 20px;">
        <van-address-list
          v-model="chosenAddressId"
          :list="addressList"
          default-tag-text="默认"
          @add="onAdd"
        >
          <template #default>
            <div class="hc-address-button">
              <van-button @click="handlerOrder" class="hc-button" block round type="primary">确认下单</van-button>
            </div>
          </template>
        </van-address-list>
      </div>
    </van-popup>
    <!--  -->
    <van-sku
      v-model="showSku"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :quota="1"
      :initial-sku="initialSku"
      :show-add-cart-btn="false"
      @buy-clicked="onBuyClicked"
    />

    <van-popup
      v-model="showConsult"
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="hc-consult-box">
        <div class="hc-consult-header">
          在线咨询
          <div class="hc-consult-close" @click="showConsult = false;">
            <van-icon style="color: #fff;transform: translateY(6px);" :size="24" name="cross"/>
          </div>
        </div>
        <!-- <iframe ref="iframe" v-lazy="`http://m.tsbeer.com?test=${shopInfo.uid}`"></iframe> -->
        <iframe ref="iframe" :src="`${locationUrl}/mobile/chat/create_room?type=1&aim_id=${shopInfo.uid}`"></iframe>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Toast } from 'vant';
import {
  postGoodsDetail,
  postAddLikeGoods,
  postAddLikeShop,
  postPayFor,
  addressList
} from "../../api/ajax";
import { HcMessageBox } from '../../components/hcMessage/index.js'

export default {
  data() {
    return {
      showConsult: false,
      goodsImg: [],
      goodsInfo: "",
      gcnt: "",
      scnt: "",
      shopInfo: "",
      actions: [
        { name: '送货上门' },
        { name: '自提' }],
      showSheet: false,
      showAddress: false,
      chosenAddressId: "",
      addressList: [],
      sku:  {
        tree: [],
        list: [],
        price: '1.00', // 默认价格（单位元）
        none_sku: false, // 是否无规格商品
        hide_stock: false, // 是否隐藏剩余库存
        stock_num: 9999
      },
      goods: {
        picture: 'https://wecan.keinadd.com/public/uploads/member/head_img/20200213/f0c2ac734fccb446530825612965d019.png'
      },
      messageConfig: {},
      initialSku: {},
      goodsId: '946755',
      showSku: false,
      selectedSkuComb: {}
    };
  },
  components: {
  },
  methods: {
    handlerConsult() {
      if(!!this.shopInfo.uid) {
        this.showConsult = true;
        // window.location.href = `${this.publicUrl}/mobile/chat/create_room?type=1&aim_id=${this.shopInfo.uid}`
      };
    },
    onBuyClicked(params) {
      console.log(params)
      this.selectedSkuComb = params.selectedSkuComb || {}
      this.showSku = false;
      this.showSheet = true;
    },
    handlerOrder() {
      if(this.chosenAddressId) {
        this.buyThis(this.chosenAddressId)
      } else {
        this.$toast('请选择您的收货地址')
      }
    },
    onAdd() {
      window.location.href = `${this.locationUrl}/mobile/user/address_list_shop?id=${this.$route.query.id}`
    },
    onEdit() {

    },
    async onSelect(item) {
      if(item.name === "送货上门") {
        this.showAddress = true;
        let result = await addressList();
        result.forEach(item => {
          item.id = item.address_id;
          item.name = item.name;
          item.tel = item.telephone;
          item.address = item.address
        })
        this.chosenAddressId = (result[0] || {}).id;
        this.addressList = result;
      }else {
        this.buyThis('')
      }
      this.showSheet = false;
    },
    go_store() {
      this.jump("detail", {
        id: this.shopInfo.b_id
      });
    },
    async postGoodsDetail() {
      let id = this.$route.query.id;
      const result = await postGoodsDetail({
        id
      });
      if (result) {
        this.goodsImg = result.goods_img_list;
        this.goodsInfo = result.goods_info;
        this.shopInfo = result.shop_info;
        this.gcnt = result.gcnt;
        this.scnt = result.scnt;
        let tree = result.option_list || []
        tree.forEach(item => {
          item.imgUrl = this.publicUrl + item.filepath
          item.previewImgUrl = this.publicUrl + item.filepath
        })
        this.sku.price = this.goodsInfo.price;
        this.goods.picture = this.publicUrl + this.goodsInfo.filepath;
        if(tree.length > 0) {
          this.sku.tree = [
            {
              k: '规格',
              v: tree,
              k_s: 's1'
            }
          ];
          tree.forEach(item => {
            this.sku.list.push({
              id: item.id,
              price: parseFloat(item.price) * 100,
              s1: item.id,
              stock_num: 99999
            })
          })
          this.initialSku = {
            s1: tree[0].id,
          }
        }else {
          this.sku.none_sku = true;
        }
      }
    },
    async likeIt(event) {
      let id = this.$route.query.id;
      const result = await postAddLikeGoods({
        id
      });
      // console.log(result.code);
      var collect_goods = this.$refs.collect_goods.innerHTML;
      // console.log(event.target.className);
      if (result.code === 1) {
        Toast.success("取消收藏成功");
        event.target.className = "van-icon van-icon-like-o";
        this.$refs.like.style.color = "#c6c5c5";
        this.$refs.collect_goods.innerHTML = Number(collect_goods - 1);
      } else {
        event.target.className = "van-icon van-icon-like";
        Toast.success("收藏成功");
        this.$refs.collect_goods.innerHTML = Number(collect_goods + 1);
        this.$refs.like.style.color = "#f8942c";
      }
    },
    async likeShop() {
      let id = this.shopInfo.b_id;
      const result = await postAddLikeShop({
        id
      });
      var num = this.$refs.collectNum.innerHTML;

      if (result.code === 2) {
        this.$refs.likeShop.style.color = "#fff";
        this.$refs.likeShop.style.backgroundColor = "#f8942c";
        this.scnt += 1;
      } else {
        this.$refs.likeShop.style.backgroundColor = "#eeeeee";
        this.$refs.likeShop.style.color = "black";
        this.scnt -= 1;
      }
    },
    //立即购买
    async buyThis(address_id = '') {
      let goods_id = this.goodsInfo.id;
      let params = {};
      params.goods_id = goods_id;
      params.option_id = this.selectedSkuComb.id || ''
      if(address_id) {
        params.address_id = address_id
      }
      const result = await postPayFor(params);
      if (result.code == 1) {
        if(result.p) {
          let _this = this;
          window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
            'appId': result.p.appId + '',
            'timeStamp': result.p.timestamp + '',
            'nonceStr': result.p.nonceStr + '',
            'package': result.p.package + '',
            'signType': result.p.signType + '',
            'paySign': result.p.paySign + ''
          }, function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              HcMessageBox("您已下单成功!");
              setTimeout(() => {
                HcMessageBox.close()
                _this.jump('home')
              }, 1000)
            } else if (res.err_msg === 'get_brand_wcpay_request:fail') {
              alert('支付失败，请重新支付')
            }
          })
        } else {
          HcMessageBox(result.msg || '下单成功');
          setTimeout(() => {
            HcMessageBox.close()
            this.jump('home')
          }, 1000)
        }
        this.showAddress = false;
      } else {
        this.$toast(result.msg);
      }
    }
  },
  mounted() {
    this.postGoodsDetail();
  }
};
</script>

<style lang="scss" scoped>
// .van-address-list {
//   height: 420px;
//   overflow: scroll;
//   .van-radio-group {
//     height: 100%;
//   }
// }
.hc-consult-box {
  height: calc(100% - 40px);
  position: relative;
  padding-top: 40px;
  .hc-consult-header {
    position: absolute;
    height: 40px;
    width: 100%;
    top: 0px;
    left: 0px;
    background-color: #f8942c;
    color: #ffffff;
    text-align: center;
    line-height: 40px;
    font-size: 14px;
    .van-popup__close-icon {
      color: #fff;
    }
    .hc-consult-close {
      position: absolute;
      right: 15px;
      top: 0px;
      bottom: 0px;
    }
  }
  iframe {
    width: 100%;
    height: 100%;
    border: none;
  }
}
.goods-detail {
  padding-bottom: px2rem(50);
}
.hc-address-button {
  position: fixed;
  left: 0px;
  width: 100%;
  padding: 0px 16px;
  box-sizing: border-box;
  bottom: 50px;
}
  .van-address-item__edit {
    display: none !important;
  }
.top-goods {

  width: 95%;
  margin: 0 auto;
  .goods-title {
    height: px2rem(150);
    // background-color: red;
    .top {
      height: px2rem(90);
      box-sizing: border-box;
      font-weight: bold;
      padding-top: px2rem(20);
      .left {
        font-size: px2rem(18);
        width: 75%;
        float: left;
      }
      .right {
        width: 25%;
        padding-top: px2rem(10);
        float: left;
        display: flex;
        justify-content: center;
        align-items: center;
        div {
          float: left;
          margin-left: px2rem(15);
        }
      }
    }
    .bottom {
      .now-price {
        color: #f8942c;
        font-size: px2rem(14);
        font-weight: bold;
        span {
          font-size: px2rem(12);
          font-weight: normal;
          border: #f8942c px2rem(1) solid;
          padding: px2rem(1) px2rem(4);
        }
      }
      .before-price {
        color: #cdcccc;
        font-size: px2rem(13);
        padding-top: px2rem(5);
      }
    }
  }

  .after-img {
    height: px2rem(40);
    color: #acacac;
    font-size: px2rem(10);
    box-sizing: border-box;
    padding-top: px2rem(15);
    .left {
      float: left;
    }
    .right {
      width: px2rem(100);
      background-color: #eeeeee;
      height: px2rem(20);
      border-radius: px2rem(20);
      float: right;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.store-detail {
  height: px2rem(150);
  border-bottom: #f4f4f4 px2rem(8) solid;
  border-top: #f4f4f4 px2rem(8) solid;
  .store-top {
    height: px2rem(90);
    .left-head {
      width: 23%;
      height: px2rem(90);
      background-color: #fff;
      float: left;
      display: flex;
      justify-content: center;
      align-items: center;
      .head {
        width: px2rem(56);
        height: px2rem(56);
        border-radius: px2rem(5);
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .address {
      width: 75%;
      float: left;
      box-sizing: border-box;
      padding-top: px2rem(16);
      height: px2rem(90);
      .store-name {
        // font-weight: bold;
        font-size: px2rem(16);
        line-height: px2rem(30);
      }
      .add {
        margin-top: px2rem(5);
        font-size: 0.26rem;
      }
    }
  }
  .store-bottom {
    height: px2rem(55);
    width: 93%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    .left,
    .right {
      width: 50%;
      height: px2rem(55);
      line-height: px2rem(40);
      text-align: center;
      font-size: px2rem(14);
      color: #1c1c1c;
      display: flex;
      justify-content: center;
      align-items: center;
      div {
        width: px2rem(160);
        height: px2rem(40);
        background-color: #eeeeee;
        border-radius: px2rem(9);
      }
    }
  }
}

.comment {
  height: px2rem(45);
  // background-color: red;
  div {
    width: 95%;
    margin: 0 auto;
    font-size: px2rem(14);
    line-height: px2rem(45);
  }
}

.no-comment {
  height: px2rem(230);
  background-color: #eeeeee;
  line-height: px2rem(230);
  text-align: center;
}

.buy {
  width: 100%;
  height: px2rem(50);
  line-height: px2rem(50);
  background-color: #fff;
  position: fixed;
  bottom: 0;
  margin-top: px2rem(5);
  font-size: 0.28rem;
  border-top: #eeeeee px2rem(1) solid;
  .now-buy {
    margin: 0 auto;
    text-align: center;
  }
}
</style>
